
// 105.从前序与中序遍历序列构造二叉树
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        // 根据前序遍历确定根节点,根据中序确定左右子树
        int n = inorder.size();
        unordered_map<int , int> m ;
        for(int i = 0 ; i < n ; i++)    m[inorder[i]] = i;
        int pos = 0;

        function<TreeNode*(int , int)> dfs = [&](int left , int right)->TreeNode*
        {
            if(left > right) return nullptr;
            TreeNode *root = new TreeNode;
            root->val = preorder[pos];
            int index = m[preorder[pos++]];
            root->left = dfs(left , index - 1);
            root->right = dfs(index + 1 , right);
            
            return root;
        };
        return dfs(0 , n - 1);
    }
};